/*
 *  Copyright 2007-2008 by Matthias Buch-Kromann <mbk.isv@cbs.dk>.
 *  *
 *  This file is part of the Open-source Dependency Toolkit (OSDT),
 *  see http://code.google.com/p/open-source-dependency-toolkit.
 *  
 *  The OSDT is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as 
 *  published by the Free Software Foundation, either version 3 of 
 *  the License, or (at your option) any later version.
 * 
 *  The OSDT is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 * 
 *  You should have received a copy of the GNU Lesser General Public 
 *  License along with the OSDT in the files COPYING and COPYING.LESSER.
 *  If not, see http://www.gnu.org/licenses.
 */

package org.osdtsystem.functions;

import java.util.List;
import org.osdtsystem.graphs.GraphAccessor;
import org.osdtsystem.values.Augmentation;

/**
 *
 * @param <V> 
 * @author Matthias Buch-Kromann <mbk.isv@cbs.dk>
 */
public class FuncThe<V> extends AbstractSingletonFunction<V>
        implements AugmentationFunction<V> {
    private Function<? extends V> generator;
    private String variable;
    
    public FuncThe(String variable, Function<? extends V> generator) {
        super(generator);
        this.variable = variable;
        this.generator = generator;
        if (variable != null)
            addLocalFreeVariable(variable);
    }
    
    public FuncThe(FuncVariable<V> var, Function<? extends V> generator) {
        this(var.name(), generator);
    }
    
    public FuncThe(Function<? extends V> generator) {
        this((String) null, generator);
    }
    
    
    @Override
    public V _singletonFunctionValue(LocalFunction<?, ?> caller, FunctionContext context,
            GraphAccessor accessor) {
        // Compute edge
        List<? extends V> values = generator.functionValue(caller, context, accessor);
        V value = (values.size() == 1) ? values.get(0) : null;
        
        // Set context variable if requested
        if (variable != null && value != null)
            context.pushVariable(variable, value);
        
        // Return node
        return value;
 }

    @Override
    public Augmentation computeAugmentation(LocalFunction<?, ?> caller, FunctionContext context, GraphAccessor accessor, Augmentation augmentation) {
        singletonFunctionValue(caller, context, accessor);
        return augmentation;
    }

    @Override
    public boolean restoreContextState() {
        return false;
    }

    @Override
    void toStringBuilder(FunctionStringBuilder builder) {
        builder.addParameter("var", variable);
        builder.addSubfunction(generator);
    }
}

   